package com.snail.service.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.mapper.BizProductCategoryMapper; // 假设Mapper路径
import com.snail.model.pojo.mall.BizProductCategory;
import com.snail.service.IBizProductCategoryService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class BizProductCategoryServiceImpl extends ServiceImpl<BizProductCategoryMapper, BizProductCategory>
        implements IBizProductCategoryService {

    @Override
    public List<BizProductCategory> listAllCategories() {
        LambdaQueryWrapper<BizProductCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizProductCategory::getDeleted, 0) // 仅查未删除
                .orderByAsc(BizProductCategory::getSort); // 按排序升序
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<BizProductCategory> listCategoryTree() {
        List<BizProductCategory> allCategories = listAllCategories();
        return buildTree(allCategories, 0L); // 从一级分类（parent_id=0）开始构建
    }

    // 递归构建树形结构
    private List<BizProductCategory> buildTree(List<BizProductCategory> allCategories, Long parentId) {
        List<BizProductCategory> tree = new ArrayList<>();
        for (BizProductCategory category : allCategories) {
            if (parentId.equals(category.getParentId())) {
                List<BizProductCategory> children = buildTree(allCategories, category.getId());
                category.setChildren(children); // 绑定子分类
                tree.add(category);
            }
        }
        return tree;
    }
}
